package cn.bdqn.layui.config;

import cn.bdqn.layui.entity.Menu;
import cn.bdqn.layui.entity.Role;
import cn.bdqn.layui.mapper.MenuMapper;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;

@Component
public class CFSMS  implements FilterInvocationSecurityMetadataSource {

    //路径匹配符 直接用以匹配路径
    //ant风格路径匹配器
    AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Resource
    MenuMapper menuMapper;

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        //获取当前用户的请求地址
        String url =((FilterInvocation)object).getRequestUrl();
        //从数据库中查询出所有路径
        List<Menu> menuList = menuMapper.getMenus();
        for (Menu menu :menuList){
            if(antPathMatcher.match(menu.getUrl(),url)){
                List<Role> roleList = menu.getRoles();
                String[] roleStr =new String[roleList.size()];
                for (int i = 0; i < roleStr.length; i++) {
                    roleStr[i] = roleList.get(i).getName();
                }
                //将筛选出来的url路径所具有的角色返回出去
                return SecurityConfig.createList(roleStr);
            }
        }
        //如果没有匹配上了就返回一个默认角色，作用好比一个标记
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {

        return FilterInvocation.class.isAssignableFrom(aClass);
    }
}
